package com.mc.read.common.util;

import com.mc.read.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @author liuhao
 * @date 2019/6/26 11:51
 */
@Slf4j
public class HttpClientUtil {

    private final static int SOCKET_TIMEOUT = 60000;//单位ms 从服务器读取数据的timeout
    private final static int CONNECTION_TIMEOUT = 60000;//单位ms 和服务器建立连接的timeout
    private final static int CONNECTION_REQUEST_TIMEOUT = 3000;//单位ms 从连接池获取连接的timeout
    private RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(SOCKET_TIMEOUT)
            .setConnectTimeout(CONNECTION_TIMEOUT)
            .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
            .build();

    private static HttpClientUtil instance = null;

    private HttpClientUtil() {
    }

    /**
     * 单例获取httpClietnUtil实例
     *
     * @return httpClietnUtil实例
     */
    public static HttpClientUtil getInstance() {
        if (instance == null) {
            instance = new HttpClientUtil();
        }
        return instance;
    }



    /**
     * 发送 post请求
     * @param httpUrl 地址
     * @param params  请求参数
     * @param charset 字符编码
     * @param contentType  contentType跟请求参数要对应如：params是json根式，contentType为application/json
     */
    public String sendHttpPost(String httpUrl, String params,String charset,String contentType)
            throws IOException {
        HttpPost httpPost = new HttpPost(httpUrl);
        //设置参数
        StringEntity stringEntity = new StringEntity(params, charset);
        stringEntity.setContentType(contentType);
        httpPost.setEntity(stringEntity);
        return sendHttpPost(httpPost);
    }



    /**
     *
     *
     * @param httpUrl
     * @return
     * @throws IOException
     */
    public String sendHttpPost(String httpUrl)
            throws Exception {
        String str ="";
        HttpPost httpPost = new HttpPost(httpUrl);
        //设置参数
        try {
            log.info("请求第三方url是>>>{}",httpUrl);
            StringEntity stringEntity = new StringEntity(httpUrl);
            httpPost.setEntity(stringEntity);
            str=sendHttpPost(httpPost);
        }catch (Exception e){
            log.error("请求第三方失败{}{}{}",httpUrl, str,e);
            throw new ServiceException(202030,"请求第三方失败");
        }
        return str;
    }





    /**
     * 发送Post请求
     * @param httpPost
     * @return
     */
    private String sendHttpPost(HttpPost httpPost) throws IOException {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        // 创建默认的httpClient实例.
        httpClient = HttpClients.createDefault();

        httpPost.setConfig(requestConfig);
        // 执行请求
        response = httpClient.execute(httpPost);
        entity = response.getEntity();
        responseContent = EntityUtils.toString(entity, "UTF-8");
        try {
            // 关闭连接,释放资源
            if (response != null) {
                response.close();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseContent;
    }


    private String sendHttpget(HttpGet httpget) throws IOException {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        // 创建默认的httpClient实例.
        httpClient = HttpClients.createDefault();

        httpget.setConfig(requestConfig);
        // 执行请求
        response = httpClient.execute(httpget);
        entity = response.getEntity();
        responseContent = EntityUtils.toString(entity, "UTF-8");
        try {
            // 关闭连接,释放资源
            if (response != null) {
                response.close();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseContent;
    }


    public String sendHttpget(String httpUrl)
            throws Exception {
        String str ="";
        HttpGet httpGet = new HttpGet(httpUrl);
        //设置参数
        try {
            log.info("请求第三方url是>>>{}",httpUrl);
//            StringEntity stringEntity = new StringEntity(httpUrl);
//            httpGet.setEntity(stringEntity);
            str=sendHttpget(httpGet);
        }catch (Exception e){
            log.error("请求第三方失败{}{}",httpUrl, str);
        }
        return str;
    }


}